package com.linchong.concurrency.chapter7;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author:linchong
 * @CreateTime:2020-01-06 22:41
 * @Description:同步代码块和同步方法
 */
@Slf4j
public class SynchronizedRunnable implements Runnable {
	private int index = 1;
	private final static int MAX = 500;

	private final Object MONITOR = new Object();

	/**
	 * synchronized锁住的对象是this，即SynchronizedRunnable实例
	 * public synchronized void run() {
	 * while(true){
	 * if(index>MAX){
	 * break;
	 * }
	 * try {
	 * Thread.sleep(5);
	 * } catch (InterruptedException e) {
	 * e.printStackTrace();
	 * }
	 * log.info("{} 的号码是{}",Thread.currentThread(),(index++));
	 * }
	 * }
	 */
	@Override
	public void run() {
		while (true) {
			if (ticket()) {
				break;
			}

		}
	}

	private synchronized boolean ticket() {
		if (index > MAX) {
			return true;
		}
		try {
			Thread.sleep(5);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		log.info("{}的号码是：{}", Thread.currentThread(), (index++));
		return false;
	}
}
